/**
 * 
 */
package com.net.shop.car.manager.ui.head;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.net.shop.car.manager.BaseFragment;
import com.net.shop.car.manager.R;
import com.net.shop.car.manager.api.model.HeadPicInfo;
import com.net.shop.car.manager.api.model.HeadPicture;
import com.net.shop.car.manager.api.volley.VolleyCenter;
import com.net.shop.car.manager.api.volley.VolleyListenerImpl;
import com.net.shop.car.manager.api.volley.request.GetActivityInfo;
import com.net.shop.car.manager.api.volley.response.ActivityInfoResponse;
import com.net.shop.car.manager.ui.MainActivity;
import com.net.shop.car.manager.ui.chezhoubian.SellerDialog;
import com.net.shop.car.manager.ui.html.WebviewDialog;
import com.net.shop.car.manager.ui.view.SwitchWidget;
import com.net.shop.car.manager.ui.view.ViewPagerScroller;
import com.net.shop.car.manager.utils.Constants.ServiceType;

/**
 * 首页
 * 
 * @author Deve
 * 
 */
@SuppressLint("HandlerLeak")
public class HeadFragment extends BaseFragment implements OnClickListener {
	/**
	 * 头部活动图
	 */
	private ViewPager mViewPager;

	/**
	 * 
	 */
	private SwitchWidget mSwitchWidget;

	/**
	 * 
	 */
	private WeatherPanel weatherPanel;
	/**
	 * 是否继续滚动
	 */
	protected boolean isContinue = true;

	/**
	 * 
	 */
	private int adPicNum;

	/**
	 * 
	 */
	private AtomicInteger what = new AtomicInteger(0);

	/**
	 * 
	 */
	private List<HeadPicture> pictures;

	/**
	 * 
	 */
	private AdvRunningAdapter pagerAdapter;

	/**
	 * 
	 */
	private Map<HeadPicture, HeadPicInfo> hMap = new HashMap<HeadPicture, HeadPicInfo>();
	
	/**
	 * 
	 */
	private WebviewDialog webviewDialog ;

	/**
	 * 
	 */
	public HeadFragment() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_head, container, false);
		initView(view);
		return view;
	}

	/**
	 * @param view
	 *            View
	 */
	private void initView(View view) {
		mViewPager = (ViewPager) view.findViewById(R.id.frag_head_pager);

		mSwitchWidget = (SwitchWidget) view.findViewById(R.id.frag_head_switch);

		weatherPanel = new WeatherPanel(view.findViewById(R.id.head_weather));

		ViewPagerScroller viewPagerScroller = new ViewPagerScroller(holder);
		viewPagerScroller.setScrollDuration(1000);
		viewPagerScroller.initViewPagerScroll(mViewPager);

		mViewPager.setOnPageChangeListener(new GuidePageChangeListener());

		mViewPager.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_MOVE:
					isContinue = false;
					break;
				case MotionEvent.ACTION_UP:
					isContinue = true;
					break;
				default:
					isContinue = true;
					break;
				}
				return false;
			}
		});

		pagerAdapter = new AdvRunningAdapter();

		mViewPager.setAdapter(pagerAdapter);

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					if (isContinue) {
						if (adPicNum > 0) {
							viewHandler.sendEmptyMessage(what.get());
							whatOption();
						}
					}
				}
			}

		}).start();

		view.findViewById(R.id.frag_head_chezhoubian).setOnClickListener(this);
		view.findViewById(R.id.frag_head_daijia).setOnClickListener(this);
		view.findViewById(R.id.frag_head_lujiu).setOnClickListener(this);
		view.findViewById(R.id.frag_head_tuoche).setOnClickListener(this);
		view.findViewById(R.id.frag_head_weizhang).setOnClickListener(this);
		initPagerInidicators();
		// mSwitchWidget.setItemSelected(def);
	}

	private void initPagerInidicators() {
		adPicNum = pictures == null ? 0 : pictures.size();
		mSwitchWidget.removeAllViews();
		for (int i = 0; i < adPicNum; i++) {
			View view = new View(holder);
			view.setBackgroundResource(R.drawable.head_tab_bg);
			LayoutParams layoutParams = new LayoutParams(0, 10, 1);
			mSwitchWidget.addView(view, layoutParams);
		}
		mSwitchWidget.setItemSelected(0);
	}

	private void whatOption() {
		what.incrementAndGet();
		if (what.get() > adPicNum - 1) {
			what.getAndAdd(-adPicNum);
		}
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			Log.e("HeadFragment", e.getMessage());
		}
	}

	private final Handler viewHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			mViewPager.setCurrentItem(msg.what);
			super.handleMessage(msg);
		}

	};

	private final class GuidePageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int arg0) {
			what.getAndSet(arg0);
			mSwitchWidget.setItemSelected(arg0);
		}
	}

	/**
	 * @author Deve
	 * 
	 */
	private class WeatherPanel {
		private TextView qiwenTxt;
		private TextView tianqiTxt;
		private TextView fengliTxt;
		private TextView xicheTxt;
		private TextView xingqiTxt;
		private TextView riqiTxt;

		/**
		 * @param view
		 *            View
		 */
		public WeatherPanel(View view) {
			qiwenTxt = (TextView) view.findViewById(R.id.weather_qiwen);
			tianqiTxt = (TextView) view.findViewById(R.id.weather_tianqi);
			fengliTxt = (TextView) view.findViewById(R.id.weather_fengxiang);
			xicheTxt = (TextView) view.findViewById(R.id.weather_xiche);
			xingqiTxt = (TextView) view.findViewById(R.id.weather_xiqi);
			riqiTxt = (TextView) view.findViewById(R.id.weather_riqi);
		}

		public void setQiwen(String qiwen) {
			this.qiwenTxt.setText(qiwen);
		}

		public void setTianqi(String tianqi) {
			this.tianqiTxt.setText(tianqi);
		}

		public void setFengli(String fengli) {
			this.fengliTxt.setText(fengli);
		}

		public void setRiqi(String riqi) {
			this.riqiTxt.setText(riqi);
		}

		public void setXiche(String xiche) {
			this.xicheTxt.setText(xiche);
		}

		public void setXingqi(String xingqi) {
			this.xingqiTxt.setText(xingqi);
		}
	}

	private void gotoHeadPicInfo(final HeadPicture headPicture) {
		if (webviewDialog != null && webviewDialog.isShowing()) {
			return;
		}
		HeadPicInfo headPicInfo = hMap.get(headPicture);
		if (headPicInfo == null) {
			holder.progressDialog.show();
			VolleyCenter.getVolley().addGetRequest(
					new GetActivityInfo(headPicture.getId()),
					new VolleyListenerImpl<ActivityInfoResponse>(
							new ActivityInfoResponse()) {

						@Override
						public void deleveryResponse(
								ActivityInfoResponse response) {
							holder.progressDialog.dismiss();
							if (response.isSuccess()) {
								hMap.put(headPicture, response.getHeadPicInfo());
								gotoHeadPicInfo(headPicture);
							}
						}
					});
		} else {
			webviewDialog = new WebviewDialog(holder, headPicInfo.getTitle());
			webviewDialog.setUrl(headPicInfo.getUrl());
			webviewDialog.show();
		}
	}

	private final class AdvRunningAdapter extends PagerAdapter {

		public AdvRunningAdapter() {
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public void finishUpdate(View arg0) {

		}

		@Override
		public int getCount() {
			return pictures == null ? 0 : pictures.size();
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			final HeadPicture headPicture = pictures.get(position);
			View view = holder.inflater.inflate(R.layout.head_avd_item,
					container, false);
			final ImageView iv = (ImageView) view.findViewById(R.id.avd_iv);
			final ProgressBar proBar = (ProgressBar) view
					.findViewById(R.id.avd_progress);
			if (headPicture.getLogo() == null) {
				proBar.setVisibility(View.VISIBLE);
				VolleyCenter.getVolley().addImageRequest(
						headPicture.getLogoUrl(), new Listener<Bitmap>() {
							@Override
							public void onResponse(Bitmap response) {
								proBar.setVisibility(View.GONE);
								headPicture.setLogo(response);
								iv.setImageBitmap(response);
							}
						}, new ErrorListener() {
							@Override
							public void onErrorResponse(VolleyError error) {
								proBar.setVisibility(View.GONE);
							}
						});
			} else {
				proBar.setVisibility(View.GONE);
				iv.setImageBitmap(headPicture.getLogo());
			}
			iv.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					gotoHeadPicInfo(headPicture);
				}
			});
			container.addView(view, 0);
			return view;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.frag_head_lujiu:
			gotoLuJiu();
			break;
		case R.id.frag_head_daijia:
			gotoDaiJia();
			break;
		case R.id.frag_head_chezhoubian:
			gotoCheZhouBian();
			break;
		case R.id.frag_head_tuoche:
			gotoTuoChe();
			break;

		case R.id.frag_head_weizhang:
			gotoWeiZhange();
			break;

		default:
			break;
		}
	}

	private void gotoWeiZhange() {
		// TODO Auto-generated method stub

	}

	private void gotoTuoChe() {
		SellerDialog sellerDialog = new SellerDialog(holder,
				ServiceType.pullcar);
		sellerDialog.show();
	}

	private void gotoCheZhouBian() {
		((MainActivity) holder).gotoCheZhouBian();
	}

	private void gotoDaiJia() {
		SellerDialog sellerDialog = new SellerDialog(holder, ServiceType.travel);
		sellerDialog.show();
	}

	private void gotoLuJiu() {
		SellerDialog sellerDialog = new SellerDialog(holder,
				ServiceType.waysave);
		sellerDialog.show();
	}

	/**
	 * @param headPictures
	 *            List<HeadPicture>
	 */
	public void notifyHeadPictures(List<HeadPicture> headPictures) {
		pictures = headPictures;
		initPagerInidicators();
		pagerAdapter.notifyDataSetChanged();
	}
}
